'''
作者：皮皮陈
功能：用Tensorflow搭一个简单的神经网络
备注：沉迷机器学习无法自拔
//        .==.        .==.
//       //`^\\      //^`\\
//      // ^ ^\(\__/)/^ ^^\\
//     //^ ^^ ^/6  6\ ^^ ^ \\
//    //^ ^^ ^/( .. )\^ ^ ^ \\
//   // ^^ ^/\| v""v |/\^ ^ ^\\
//  // ^^/\/ /  `~~`  \ \/\^ ^\\
//  -----------------------------
/// HERE BE DRAGONS
'''
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#添加神经网络层函数,参数分别为输入值，输入值大小，输出值和激励函数
def add_layer(inputs,in_size,out_size,activation_function = None):
    weights = tf.Variable(tf.random_normal([in_size,out_size])) #因为在生成初始参数时，随机变量(normal distribution)会比全部为0要好很多
    bias = tf.Variable(tf.zeros([1,out_size]) + 0.1) #0.1的矩阵
    if activation_function==None:
        Wx_plus_b = tf.matmul(inputs,weights) + bias#神经网络没激活就是用线性模型
        outputs = Wx_plus_b
    else:
        outputs = tf.nn.relu(inputs)
    return  outputs


#构建数据，如果有外部数据，修改这部分
x_data = np.linspace(-1,1,300, dtype=np.float32)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data) - 0.5 + noise

xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])

#可视化
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data,y_data)
plt.ion()
plt.show()

#搭建神经网络模型
a1 = add_layer(xs,1,10,activation_function=tf.nn.relu)
prediction = add_layer(a1,1,10,activation_function=None)
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))#均方差求和再平均
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
#训练
for i in range(1000):
    sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
    if i % 100 == 0:
        prediction_value = sess.run(prediction, feed_dict={xs: x_data})
        lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
        plt.pause(0.1)
        print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))


